package com.cherry.androidviewdemo.widget

import android.content.Context
import android.graphics.*
import android.support.annotation.ColorInt
import android.util.AttributeSet
import android.widget.TextView
import com.cherry.androidviewdemo.R

/**
 * @author DongMS
 * @since 2020/6/2
 */
class ColorTextView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : TextView(context, attrs, defStyleAttr) {

    var normalTextColor = Color.BLACK

    var changeTextColor = Color.RED

    private val normalPaint: Paint

    private val changePaint: Paint

    var direction = Direction.LEFT_TO_RIGHT

    var progress = 0.0f
        set(value) {
            field = value
            invalidate()
        }

    private val textRect = Rect()

    private val clipRect = RectF()

    init {

        val array = context.obtainStyledAttributes(attrs, R.styleable.ColorTextView)
        normalTextColor = array.getColor(R.styleable.ColorTextView_normalColor, normalTextColor)
        changeTextColor = array.getColor(R.styleable.ColorTextView_changeColor, changeTextColor)
        array.recycle()

        normalPaint = initPaint(normalTextColor)
        changePaint = initPaint(changeTextColor)

    }


    private fun initPaint(@ColorInt textColor: Int): Paint {
        return Paint(Paint.ANTI_ALIAS_FLAG or Paint.DITHER_FLAG).apply {
            color = textColor
            textSize = this@ColorTextView.textSize
        }
    }

    //目前只考虑到单行文本的情况，以后写多行文本
    override fun onDraw(canvas: Canvas) {
//        super.onDraw(canvas)

        val text = text.toString()
        val middle = progress * width

        //方向表示原先的颜色->选中的颜色
        if (direction == Direction.LEFT_TO_RIGHT) {
            drawText(changePaint, text, canvas, 0f, middle)
            drawText(normalPaint, text, canvas, middle, width * 1f)
        } else {
            drawText(changePaint, text, canvas, width - middle, width * 1f)
            drawText(normalPaint, text, canvas, 0f, width - middle)
        }
    }

    private fun drawText(paint: Paint, text: String, canvas: Canvas, leftStart: Float, rightEnd: Float) {
        canvas.save()
        clipRect.set(leftStart, 0f, rightEnd, height * 1f)
        canvas.clipRect(clipRect)

        paint.getTextBounds(text, 0, text.length, textRect)
        val dx = (width - textRect.width()) / 2f

        val fontMetrics = paint.fontMetrics
        val dy = (fontMetrics.bottom - fontMetrics.top) / 2 - fontMetrics.bottom
        val baseLine = height / 2f + dy
        canvas.drawText(text, dx, baseLine, paint)

        canvas.restore()
    }

    enum class Direction {
        LEFT_TO_RIGHT,
        RIGHT_TO_LEFT
    }

}